from server import *
import datetime
import time

# datetime.datetime.now()

def save_to_file(path, data):
	fd = open(path, "a+")
	fd.write(data)
	fd.close()

class HJ212_2017_ServerHandler(baseServerHandler):
	def recvDataDispose(self, data):
		print("{} recv:".format(self.client_address),self.data)
		save_to_file(filepath, "{} recv:".format(self.client_address) + str(self.data) + '\n')

if __name__=="__main__":		# 测试程序

	current = 0
	filepath = "test-data/test-data1.txt"
	save_to_file(filepath, '\r\n' + str(datetime.datetime.now()) + '\r\n')

	server = TCPServer(port=8000, Handler=HJ212_2017_ServerHandler)
	while True:
		cmd = input("cmd->")
		if cmd == "disconnet":
			server.disconnet()
		elif cmd == "client":
			print("client:")
			ClientList = server.getClientList()
			for i in range(0, len(ClientList)):
				print(i, ".", ClientList[i])
		elif "CN=" in cmd:
			client_list = server.getClientList()
			if current < len(client_list):
				send_data = "##0071QN=20160801085857223;ST=32;CN=xxxx;PW=123456;MN=12345678;Flag=5;CP=&&&&0000\r\n"
				cmd_list = cmd.split()
				send_data = send_data.replace("CN=xxxx", cmd_list[0])
				if len(cmd_list) > 1:
					send_data = send_data.replace("CP=&&&&", "CP=&&" + cmd_list[1] + "&&")
				send_data = send_data.replace("##0071", "##%04d"%(len(send_data) - 6 - 6))
				server.sendClient(client_list[current], send_data)
				print("{} send:".format(client_list[current]), send_data)
				save_to_file(filepath, send_data)
			else:
				print("no connet")

		
		



























